package com.nut.article.timer;

import com.nut.article.cache.CacheInMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TimerService {

    @Autowired
    private CacheInMap cacheInMap;

//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;
//
//    @Autowired
//    private ValueOperations<String, Object> valueOperations;

    public static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("cacheTimerThread");
            t.setDaemon(true);
            return t;
        }
    });

    public TimerService() {
        EXECUTOR.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                cacheObjectClean();
            }
        }, 1, 1, TimeUnit.MINUTES);
    }

    /**
     * 清理过期缓存对象
     */
    private void cacheObjectClean() {
        try {
            cacheInMap.ClearExpiredObject();
            System.out.println("start cache time clean!!");
        } catch (Throwable e) {
            log.error("cacheObjectClean_error", e);
        }
    }

}


